<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1 mv-text="msg"></h1>
        <h1 mv-text="msg"></h1>
        <h1 mv-text="msg"></h1>
        <input type="text" mv-oninput="setMsg">
        <input type="text" mv-oninput="setMsg">
        <input type="text" mv-oninput="setMsg">

        <h1 mv-text="info"></h1>
        <input type="text" mv-oninput="setInfo">


    </div>
</body>
<script>
    function Mvvm(options){
        // 当构造器被调用时，通过传入配置的el属性，找到需要操作的DOM节点作为容器
        this.root = document.querySelector(options.el);
        let depts = {
            notiy:function(argName,nv){
                // console.log(this,this[argName],argName);
                this[argName].forEach(dom => {
                    // console.log(dom);
                    dom.textContent = nv;
                });
            }
        };

        for (let key in options.data) {
            // 获取容器中和 该变量有关的DOM元素
            depts[key] = this.root.querySelectorAll(`[mv-text=${key}]`);
            // 将仓库中的所有数据变量，以劫持方式定义到当前构建实例的根属性上
            Object.defineProperty(this,key,{
                configurable:true,
                enumerable:true,
                get(){
                    return options.data[key];
                },
                set(nv){
                    options.data[key] = nv;
                    depts.notiy(key,nv)
                }
            });

            depts.notiy(key,options.data[key])

        }
        let eventDom = this.root.querySelectorAll("[mv-oninput]");
        // console.log(eventDom);
        eventDom.forEach(dom=>{
            let mkey = dom.getAttribute("mv-oninput");
            // console.log( options.methods[mkey] );
            dom.addEventListener("input",(event)=>{
                options.methods[mkey].call(this,event);
            })
        })
        // console.log(depts);
    }

    var vm = new Mvvm({
        el:"#app",
        data:{
            msg:"数据变量msg",
            info:"数据变量info",
        },
        methods: {
            setMsg(e){
                // console.log(this,e,"aaaa");
                this.msg = e.target.value
            },
            setInfo(e){
                this.info = e.target.value
            }
        },
    })
</script>
</html>